import { feedApi } from '/api/feed'
import { checkAuth } from '/store/actions'
import { isLogin } from '/store/mutations'
import { $event, $utils } from '/utils'
Page({
  data: {
    navData: [
      { name: '集梦交流赛', id: 1, page: 0, isLastpage: false },
      { name: '集梦单挑赛', id: 2, page: 0, isLastpage: false },
      { name: '集梦榜单', id: 3, page: 0, isLastpage: false },
    ],
    cur: 1,
    query: {
      only_video: false,
      category: 0 as number,
      limit: 15,
    },
    closeable: false,
    list: [] as any[],
    follower: false,
    scrollClass: false,
    user: {},
    currentIndex: 1,
    activitylist: [] as any,
  },
  onLoad() {
    $event.on('after:login', this, () => {
      this.getMatchList()
    })
    this.getMatchList()
  },
  async onPullDownRefresh() {
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    if (this.data.navData[this.data.cur].isLastpage) {
      wx.showToast({
        title: '已没有更多',
        icon: 'none',
        duration: 1000,
      })
    } else {
      this.getUserList(true)
    }
  },
  onPageScroll() {
    this.fixedTitle()
  },
  /** 判断是否滚动到了导航 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#header').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] && res[0].bottom < 0,
      })
    })
  },

  toChangeCurrent(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id as number
    if (id === this.data.cur) return
    this.setData({
      cur: id,
    })
    this.updateCurrentTable(id)
  },
  async changeCurrent(e: any) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    this.updateCurrentTable(index)
  },
  async go_baoming(options: any) {
    console.log(options.currentTarget.dataset.id)
    const id = options.currentTarget.dataset.id
    if (!isLogin()) {
      console.log('not login list0')
      await checkAuth()
    } else {
      wx.navigateTo({
        url: `/pages/match/baoming/baoming?event_id=${id}`,
      })
    }
  },
  onShareAppMessage() {
    return {
      path: $utils.getSharePath(),
    }
  },
  onShareTimeline() {
    return {
      title: '集梦116城市赛',
      query: 'from=timeline',
      imageUrl: 'https://houdong.ecoac.cn/images/share.png',
    }
  },
  async updateCurrentTable(index: any) {
    if (!isLogin()) {
      await checkAuth()
    }
    const {
      data: {
        navData,
        query: { },
      },
    } = this
    this.setData(
      {
        currentIndex: parseInt(index),
        category: navData[parseInt(index)].id,
        method: index < 2 ? 'normal' : 'hot',
        query: {
          ...this.data.query,
          // 设置分类
          category: navData[parseInt(index)].id,
        },
      },
      async () => {
        const loaded = wx.getStorageSync(`loaded_${index}`)
        // 是否加载过，没有加载过则执行首次加载
        if (
          loaded !== true ||
          (loaded === true && (this.data.activitylist[index] || []).length === 0)
        ) {
          // const list = await this.fetchMatchList()
          const activitylist = await this.fetchMatchList()
          this.setData({
            activitylist: activitylist.data,
          })
        }
      },
    )
  },
  chooseTab(e: WechatMiniprogram.BaseEvent) {
    const index = e.currentTarget.dataset.index
    if (index === this.data.cur) return
    this.setData({
      cur: index,
    })
    if (this.data.list[this.data.cur]) return
    this.fetchMatchList()
  },
  getCurrentDate() {
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    // console.log(`${year}-${month}-${day}`)
    return `${year}-${month}-${day}`
  },
  async getUserList(isLoadMore = false) { },
  async getMatchList() {
    const list = await this.fetchMatchList()
    for (const index in list.data) {
      list.data[index].date = list.data[index].date.slice(0, 10)
      if (list.data[index].expired_date && list.data[index].expired_date < this.getCurrentDate()) {
        list.data[index].is_expired = 1
      } else {
        list.data[index].is_expired = 0
      }
    }
    console.log(list)
    this.setData({
      activitylist: list.data,
    })
    console.log(this.data.activitylist)
  },
  async fetchMatchList(isLoadMore = false): Promise<DomoMatchListsData> {
    wx.showLoading({
      title: '加载中',
    })
    const {
      data: { query },
    } = this
    this.setData({
      loading: true,
    })
    const matchlist = await feedApi.getMatchList({
      limit: query.limit,
      category_id: this.data.currentIndex,
      page: 1,
      audited: 1,
      admin_sort: 'down',
    })
    wx.setStorageSync(`loaded_match_1`, true)
    this.setData({ loading: false })
    wx.hideLoading()
    return matchlist
  },
  async follower(e: WechatMiniprogram.BaseEvent) {
    if (this.data.follower) return
    this.setData({
      follower: true,
    })
    const index = e.currentTarget.dataset.index
    const cur = this.data.cur
    const list = this.data.list[cur]
    this.setData({
      [`list[${cur}][${index}].has_follower`]: !list[index].has_follower,
      follower: false,
    })
    wx.showToast({
      title: list[index].has_follower ? '关注成功' : '已取消关注',
      icon: 'none',
      duration: 1000,
    })
  },
})
